package com.fivetalks.client;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.fivetalks.object.Member;


public class SettingActivity extends Activity {
	Member member;
	private ImageView ivface = null;
	private ImageView ivmask = null;
	private TextView tvnickname = null;
	 
	private static final int REQ_MYFACE_ALBUM = 0;
	private static final int REQ_MYMASK_ALBUM = 1;
	private static final int REQ_MYNICKNAME = 2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);
		
		String filePath_facedefault = "/sdcard/user_image/face_1.png";
		String filePath_maskdefault = "/sdcard/user_image/mask_1.png";
		
		try{
		File facefile = new File(filePath_facedefault);
		File maskfile = new File(filePath_maskdefault);
		
		//얼굴 이미지 파일이 로컬에 없을 경우 얼굴 이미지 파일 복사
		if( !(facefile.isFile()) )
		{
			//파일생성 (복사)
			Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.face_1);
			
			File mfile = new File(filePath_facedefault, "face_1.png");
			OutputStream outStream = null;
			
			try {
				outStream = new FileOutputStream(mfile);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    
		    bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
		    try {
				outStream.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    try {
				outStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		//캐릭 이미지 파일이 로컬에 없을 경우 캐릭 이미지 파일 복
		if( !(maskfile.isFile()) )
		{
			//파일생성 (복사)
			Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.mask_1);
			
			File mfile = new File(filePath_facedefault, "mask_1.png");
			OutputStream outStream = null;
			
			try {
				outStream = new FileOutputStream(mfile);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    
		    bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
		    try {
				outStream.flush();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    try {
				outStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//	Bitmap selPhoto = Images.Media.getBitmap(getContentResolver(), selPhotoUri );
		}catch(Exception e) {
			
		}
		
		Intent intent = getIntent();
		member = (Member)intent.getSerializableExtra("member");
		
		tvnickname = (TextView)findViewById(R.id.tvNickname_activity_setting);
		tvnickname.setText(member.getNickname());
		
		//final Bitmap myBitmap = BitmapFactory.decodeFile(filePath);
		
		//SettingActivity의 닉네임 클릭 리스너 설정, SettingDialogActivity.class로 연결시킨다.

		tvnickname = (TextView)findViewById(R.id.tvNickname_activity_setting);
		tvnickname.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), SettingDialogActivity.class);
				startActivityForResult(intent, REQ_MYNICKNAME);
				
//				intent = getIntent();
//				tvnickname = (TextView)findViewById(R.id.tvNickname_activity_setting);
//				tvnickname.setText(intent.getExtras().getString("nickname"));
			}
		});
		
		ivmask = (ImageView)findViewById(R.id.ivMask);
		ivmask.setOnClickListener(new OnClickListener() {
		@Override
			public void onClick(View v) {
				// 갤러리를 호출해서 휴대폰에 저장된 이미지를 읽어들임
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");// image/jpg, image/png
				startActivityForResult(intent, REQ_MYMASK_ALBUM);
				
				//ivmask.setImageResource(R.drawable.mask_3);
				//ivmask.setImageBitmap(myBitmap);
				
				// http://ip:port/contextroot/resources/urstory.jpg
				// ImageView는 위의 url에 있는 내용을 보여준다.
			}
		});
		
		ivface = (ImageView)findViewById(R.id.ivFace);
		ivface.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 갤러리를 호출해서 휴대폰에 저장된 이미지를 읽어들임
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");// image/jpg, image/png
				startActivityForResult(intent, REQ_MYFACE_ALBUM);
				
				//ivface.setImageResource(R.drawable.face_3);
				//ivface.setImageBitmap(myBitmap);		
			}
		});
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (requestCode == REQ_MYFACE_ALBUM) {
			Uri selPhotoUri = intent.getData();
			
			try { 
				Bitmap selPhoto = Images.Media.getBitmap(getContentResolver(), selPhotoUri );
				ivface.setImageURI(selPhotoUri);
				
				try{
					SocketClient sc = SocketClient.getInstance(null, null,
							null, null, null, null,SettingActivity.this, null);
					
					DataOutputStream dos = sc.getDos();
					dos.writeUTF("faceUpload");     
//					
//					Drawable d =ivface.getBackground();
//				    BitmapDrawable bitDw = ((BitmapDrawable) d);
//				    Bitmap bitmap = bitDw.getBitmap();
					
					// 이미지를 읽을 수 있는 inputStream을 가지고 온다.
				    ByteArrayOutputStream stream = new ByteArrayOutputStream();
				    selPhoto.compress(CompressFormat.JPEG, 0 /*ignored for PNG*/, stream); 
				    byte[] bitmapdata = stream.toByteArray();
				    ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
				    dos.writeLong(bs.available()); //파일 크기를 전송. 

				    byte[] buffer = new byte[512];
				    int readCount = 0;
				    while((readCount = bs.read(buffer)) != -1){
				    	dos.write(buffer,0, readCount);
				    }
				    
					}catch(Exception e) {
						e.printStackTrace();
					}
				
			 } catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block e.printStackTrace();
			}
		
		}
		
		if (requestCode == REQ_MYMASK_ALBUM) {
			Uri selPhotoUri = intent.getData(); 
			
			try { 
				//Bitmap selPhoto = Images.Media.getBitmap(getContentResolver(), selPhotoUri );
				ivmask.setImageURI(selPhotoUri);

	            String[] filePathColumn = {MediaStore.Images.Media.DATA};

	            Cursor cursor = getContentResolver().query(
	            		selPhotoUri, filePathColumn, null, null, null);
	            cursor.moveToFirst();

	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            String filePath = cursor.getString(columnIndex);
	            cursor.close();

	            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
	            
//				try{
					SocketClient sc = SocketClient.getInstance(null, null,
							null, null, null, null,SettingActivity.this, null);
					
					DataOutputStream dos = sc.getDos();
					dos.writeUTF("maskUpload");
					
					final Drawable d =ivmask.getBackground();
																Log.d("TAG", "ivmask image get!!!...........................1" + d.getClass().toString());
																
					//BitmapDrawable bitDw = (BitmapDrawable)d;
				    //Bitmap bitmap = bitDw.getBitmap();						    
				    // 이미지를 읽을 수 있는 inputStream을 가지고 온다.
				   
					ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
				    yourSelectedImage.compress(CompressFormat.JPEG, 0 /*ignored for PNG*/, stream); 				    											
				    byte[] bitmapdata = stream.toByteArray();
				    											Log.d("TAG", "ivmask image get!!!...........................6 :" + bitmapdata.length);
				    ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
				    
				    dos.writeLong(bs.available()); //파일 크기를 전송. 

				    byte[] buffer = new byte[512];
				    int readCount = 0;
				    while((readCount = bs.read(buffer)) != -1){
				    	dos.write(buffer,0, readCount);
				    }
				    
					}catch(Exception e) {
						e.printStackTrace();
					}
	
		}
		if (requestCode == REQ_MYNICKNAME) {
				tvnickname = (TextView)findViewById(R.id.tvNickname_activity_setting);
				tvnickname.setText(intent.getExtras().getString("nickname"));	 
		}
		
	}
	
}